<template>
  <view class="login">
    <view class="topBox">
      <view class="logo">
        <view class="logoItem"></view>
      </view>
    </view>
    <view class="getUserInfo">
      <view class="btnContainer">
        <view class="conformLogin"><AtButton type="primary" @click="judgeIsAgree">手机号一键登录</AtButton></view>
        <!-- <view class="conformLogin"><AtButton type="primary" openType="getPhoneNumber"  @getPhoneNumber="confirmLogin">手机号一键登录</AtButton></view> -->

        <view class="loginOut">
          <text  @tap="loginOut">取消登录</text>
        </view>
        
        <view class="xieyi"><checkbox :checked="isAgree" style="transform: scale(0.8);position: relative;top: -2rpx;" @tap="clickCheckBox"></checkbox>请先阅读并同意<text class="sF" @tap="gotoAgreement"> 用户协议 </text>和<text class="sF" @tap="gotoPrivacy"> 隐私协议</text></view>
      </view>

    </view>
    <AtModal :isOpened="isOpened">
        <AtModalHeader>登录提示</AtModalHeader>
        <AtModalContent>
          此次将获取您的手机号授权登录
        </AtModalContent>
        <AtModalAction> <Button @tap="isOpened=false">取消</Button> <Button openType="getPhoneNumber"  @getPhoneNumber="confirmLogin" @tap="isOpened=false">确定</Button> </AtModalAction>
    </AtModal>
  </view>
</template>

<script setup>
import './index.scss'
import { AtButton, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui-vue3'
import Taro, {useDidShow} from '@tarojs/taro'
import {get_session_key, get_user_info, login, doOrder } from '../../http/api'
import {ref, reactive} from 'vue'

const isOpened = ref(false)
const isAgree = ref(false)

const order = reactive({
  status: false,
  info: {}
})
const loginOut = () => {
  Taro.showModal({
    title: '温馨提示',
    confirmText: '暂不登录',
    content: '确认要取消登录？登陆后才能使用完整功能！',
    success: (res) => {
      if (res.confirm) {
        Taro.switchTab({
          url: `/pages/index/index`
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
  
}
const clickCheckBox = () => {
  isAgree.value = !isAgree.value
}
const judgeIsAgree = () => {
  if(isAgree.value) {
    isOpened.value = true
  } else {
    Taro.showToast({
      title: '请先阅读协议并同意',
      icon: 'none',
      duration: 2000
    })
  }

}
useDidShow(() => {
  let params =Taro.getCurrentInstance().router.params
  if(params.order) {
    order.info = JSON.parse(params.order);
    order.status = true
  }
})
// 确认登录

let openId, encryptedData, iv, phoneNumber, scopeUserInfo
 function confirmLogin (res) {
  if(res.detail.errMsg == "getPhoneNumber:ok") {
    encryptedData = res.detail.encryptedData;
    iv = res.detail.iv;
    Taro.login({success: function (wxLogin) {
      if (wxLogin.code) {
        let params = {'js_code': wxLogin.code}
        get_session_key(params).then(openIdObj => {
          if(openIdObj.code == '1000' ) {
            openId = openIdObj.data.open_id
            scopeUserInfo = {
              encryptedData,
              iv,
              open_id: openId
            }         
            get_user_info(scopeUserInfo).then(userData => {
              if (userData.code == '1000') {
                phoneNumber = userData.data.phoneNumber
                login({openid: openId, user_telphone: phoneNumber}).then(LoginData => {
                  if (LoginData.code == '1000') {
                    Taro.setStorage({
                      key: 'userData',
                      data: JSON.stringify(LoginData.data),
                      complete: async() => {
                        // 登录成功
                        Taro.setStorage({
                          key: 'wx_status',
                          data: LoginData.data.wx_status
                        })
                        if (order.status) {
                          let codeOrder = await doOrder({order_data : order.info})
                          // 跳转付款页面
                          Taro.redirectTo({
                            url: `/pages/orderDetail/index?o_order_code=${codeOrder.data.o_order_code}&from=login`
                          })
                        } else {
                          Taro.navigateBack({ delta: 2 })
                        }
                        
                      }
                    })
                  }
                  
                })
              }
            })
          } 
        })
      }
    }})
  }
}

const gotoAgreement = () => {
  Taro.navigateTo({
    url: `/pages/agreement/index`
  })
}
const gotoPrivacy = () => {
  Taro.navigateTo({
    url: `/pages/privacy/index`
  })
}
Taro.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline']
})
</script>
